package yunjiao.javatutorials.mq.component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import yunjiao.javatutorials.mq.model.MqTopicEnum;
import yunjiao.javatutorials.mq.model.Order;
import yunjiao.javatutorials.mq.model.User;

import java.math.BigDecimal;
import java.util.List;

/**
 * 业务服务：模拟查询数据库数据，选择性发送到MQ
 *
 * @author yangyunjiao
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessDataSyncService {
    private final MqMessageSender mqMessageSender;
    private final RandomOrderSupplier randomOrderSupplier;
    private final RandomUserSupplier randomUserSupplier;

    public void syncSingleUser() {
        // 1. 模拟从数据库查询数据（实际项目替换为MyBatis/JPA）
        User user = randomUserSupplier.get();

        // 2. 选择性发送（示例：只发送状态为1的用户）
        if (user.getStatus() == 1) {
            mqMessageSender.sendSingleMessage(
                    MqTopicEnum.USER_DATA_SYNC,
                    "USER",
                    user
            );
        } else {
            log.info("用户不满足发送条件：userId={}, status={}", user.getId(), user.getStatus());
        }
    }

    public void syncBatchOrder(int size) {
        // 1. 模拟批量查询（实际项目可加分页）
        List<Order> orders = randomOrderSupplier.get(size);

        // 2. 选择性发送（示例：只发送金额>100的订单）
        List<Order> sendOrders = orders.stream()
                .filter(order -> order.getAmount().compareTo(new BigDecimal("100")) > 0)
                .toList();

        if (!sendOrders.isEmpty()) {
            mqMessageSender.sendBatchMessage(
                    MqTopicEnum.ORDER_DATA_SYNC,
                    "ORDER",
                    sendOrders
            );
        } else {
            log.info("无订单满足发送条件：Amount > 100");
        }
    }
}
